package org.example;

import groovy.text.StreamingTemplateEngine;
import groovy.text.Template;
import org.apache.commons.lang3.StringUtils;
import org.example.config.ConfigLoader;
import org.fife.ui.rsyntaxtextarea.RSyntaxTextArea;
import org.fife.ui.rsyntaxtextarea.SyntaxConstants;
import org.fife.ui.rtextarea.RTextArea;
import org.fife.ui.rtextarea.RTextScrollPane;

import javax.swing.*;
import java.awt.*;
import java.awt.event.ActionEvent;
import java.awt.event.ActionListener;
import java.awt.event.WindowAdapter;
import java.awt.event.WindowEvent;
import java.util.HashMap;
import java.util.Map;

public class MainWindow {

    // 定义一个JFrame对象，表示应用程序的主窗口 frame
    private JFrame frame;
    RTextArea textArea;
    JTextField textField;
    JLabel resultLabel;
    ConfigLoader configLoader;
    StreamingTemplateEngine engine;

    // 应用程序的入口点
    public static void main(String[] args) {
        // 使用事件队列在UI线程上异步执行代码
        EventQueue.invokeLater(new Runnable() {
            public void run() {
                try {
                    UIManager.setLookAndFeel("com.sun.java.swing.plaf.windows.WindowsLookAndFeel");
                    // 创建FactoryWindow对象
                    MainWindow window = new MainWindow();
                    window.frame.setVisible(true);
                    // 设置窗口为可见状态
                } catch (Exception e) {
                    e.printStackTrace();
                }
            }
        });
    }

    // 构造方法，用于创建应用程序的主窗口
    public MainWindow() {
        configLoader = ConfigLoader.create();
        // 初始化窗口的内容
        initialize();
    }

    // 初始化窗口的内容
    private void initialize() {
        frame = new JFrame();
        frame.setTitle("SwiftSQL");
        frame.setBounds(100, 100, 620, 409);
        frame.setLocationRelativeTo(null);// 显示屏幕中间,写在设置窗体大小的后面
        frame.setDefaultCloseOperation(JFrame.EXIT_ON_CLOSE);
        // 设置标题栏图标
        frame.setIconImage(new ImageIcon(MainWindow.class.getClassLoader().getResource("cmder.png")).getImage());

        frame.getContentPane().setLayout(new BorderLayout(0, 0));

        JToolBar toolBar = new JToolBar();
        toolBar.setFloatable(false);
        frame.getContentPane().add(toolBar, BorderLayout.NORTH);

        engine = new StreamingTemplateEngine();
        DBUtil dbUtil = new DBUtil();

        JButton executeButton = new JButton("Execute");
        executeButton.setFont(new Font("宋体", Font.BOLD, 18));
        executeButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // TODO: 从配置文件中读取SQL语句模板，并替换其中的值
                // 执行数据库操作
                try {
                    if (StringUtils.isBlank(textField.getText().trim())) return;
                    String updateSql = configLoader.getConfigValue("update-sql");
                    System.out.println(updateSql);

                    Map<String, String> map = new HashMap<>();
                    map.put("txt1", textField.getText());
                    map.put("txt2", textArea.getText());
                    Template template = engine.createTemplate(updateSql);
                    String sql = template.make(map).toString();
                    System.out.println(sql);

                    int update = dbUtil.update(sql);
                    // TODO: 使用JDBC连接数据库执行SQL语句
                    // 这里需要替换SQL语句中的参数，比如使用PreparedStatement
                    // 处理执行结果并更新resultLabel的显示
                    resultLabel.setText(String.format("Update successful!\t影响了%s条", update)); // 更新成功或失败的消息
                } catch (Exception ex) {
                    ex.printStackTrace();
                    resultLabel.setText("Update failed!" + ex.getMessage());
                }
            }
        });
        toolBar.add(executeButton);

        JButton queryButton = new JButton("Query Data");
        queryButton.setFont(new Font("宋体", Font.BOLD, 18));
        queryButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                // 执行数据库操作
                try {
                    if (StringUtils.isBlank(textField.getText().trim())) return;
                    String selectSql = configLoader.getConfigValue("select-sql");
                    System.out.println(selectSql);

                    Map<String, String> map = new HashMap<>();
                    map.put("txt1", textField.getText());
                    map.put("txt2", textArea.getText());
                    Template template = engine.createTemplate(selectSql);
                    String sql = template.make(map).toString();
                    System.out.println(sql);

                    String select = dbUtil.select(sql);
                    //
                    textArea.setText(select);
                    // 设置光标位置到第一行
                    textArea.setCaretPosition(0);
                    //
                    resultLabel.setText("Query successful!" + (select == null ? " 结果为null" : "")); // 更新成功或失败的消息
                } catch (Exception ex) {
                    ex.printStackTrace();
                    resultLabel.setText("Query failed!" + ex.getMessage());
                }
            }
        });

        Component horizontalStrut = Box.createHorizontalStrut(20);
        toolBar.add(horizontalStrut);
        toolBar.add(queryButton);

        Component horizontalStrut_1 = Box.createHorizontalStrut(20);
        toolBar.add(horizontalStrut_1);

        JButton btnNewButton = new JButton("PasteTxt1");
        btnNewButton.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textField.setText("");
                textField.paste();
            }
        });
        btnNewButton.setFont(new Font("宋体", Font.BOLD, 18));
        toolBar.add(btnNewButton);

        Component horizontalStrut_2 = Box.createHorizontalStrut(20);
        toolBar.add(horizontalStrut_2);

        JButton btnNewButton_1 = new JButton("PasteTxt2");
        btnNewButton_1.addActionListener(new ActionListener() {
            public void actionPerformed(ActionEvent e) {
                textArea.setText("");
                textArea.paste();
                // 设置光标位置到第一行
                textArea.setCaretPosition(0);
            }
        });
        btnNewButton_1.setFont(new Font("宋体", Font.BOLD, 18));
        toolBar.add(btnNewButton_1);

        JPanel panel = new JPanel();
        frame.getContentPane().add(panel, BorderLayout.CENTER);
        GridBagLayout gbl_panel = new GridBagLayout();
        gbl_panel.columnWidths = new int[]{0, 0, 0};
        gbl_panel.rowHeights = new int[]{0, 0, 0, 0};
        gbl_panel.columnWeights = new double[]{0.0, 1.0, Double.MIN_VALUE};
        gbl_panel.rowWeights = new double[]{0.0, 0.0, 1.0, Double.MIN_VALUE};
        panel.setLayout(gbl_panel);

        JLabel lblNewLabel = new JLabel("Execute Result");
        lblNewLabel.setFont(new Font("宋体", Font.BOLD, 12));
        GridBagConstraints gbc_lblNewLabel = new GridBagConstraints();
        gbc_lblNewLabel.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel.gridx = 0;
        gbc_lblNewLabel.gridy = 0;
        panel.add(lblNewLabel, gbc_lblNewLabel);

        resultLabel = new JLabel("");
        resultLabel.setFont(new Font("宋体", Font.BOLD, 16));
        GridBagConstraints gbc_resultLabel = new GridBagConstraints();
        gbc_resultLabel.insets = new Insets(0, 0, 5, 0);
        gbc_resultLabel.gridx = 1;
        gbc_resultLabel.gridy = 0;
        panel.add(resultLabel, gbc_resultLabel);

        JLabel lblNewLabel_1 = new JLabel("Where Condition:");
        lblNewLabel_1.setFont(new Font("宋体", Font.BOLD, 12));
        GridBagConstraints gbc_lblNewLabel_1 = new GridBagConstraints();
        gbc_lblNewLabel_1.insets = new Insets(0, 0, 5, 5);
        gbc_lblNewLabel_1.anchor = GridBagConstraints.EAST;
        gbc_lblNewLabel_1.gridx = 0;
        gbc_lblNewLabel_1.gridy = 1;
        panel.add(lblNewLabel_1, gbc_lblNewLabel_1);

        textField = new JTextField();
        textField.setFont(new Font("宋体", Font.BOLD, 22));
        GridBagConstraints gbc_textField = new GridBagConstraints();
        gbc_textField.insets = new Insets(0, 0, 5, 0);
        gbc_textField.fill = GridBagConstraints.HORIZONTAL;
        gbc_textField.gridx = 1;
        gbc_textField.gridy = 1;
        panel.add(textField, gbc_textField);
        textField.setColumns(10);

        JLabel lblNewLabel_2 = new JLabel("Update Content:");
        lblNewLabel_2.setFont(new Font("宋体", Font.BOLD, 12));
        GridBagConstraints gbc_lblNewLabel_2 = new GridBagConstraints();
        gbc_lblNewLabel_2.insets = new Insets(0, 0, 0, 5);
        gbc_lblNewLabel_2.gridx = 0;
        gbc_lblNewLabel_2.gridy = 2;
        panel.add(lblNewLabel_2, gbc_lblNewLabel_2);

        RTextScrollPane textScrollPane = getRTextScrollPane();
        textArea = textScrollPane.getTextArea();

        //JTextArea textArea_1 = new JTextArea();
        GridBagConstraints gbc_textArea_1 = new GridBagConstraints();
        gbc_textArea_1.fill = GridBagConstraints.BOTH;
        gbc_textArea_1.gridx = 1;
        gbc_textArea_1.gridy = 2;
        panel.add(textScrollPane, gbc_textArea_1);

        // 创建窗口关闭事件的监听器
        frame.addWindowListener(new WindowAdapter() {
            @Override
            public void windowClosing(WindowEvent e) {
                // 在窗口关闭时执行你的操作
                // 这里可以是保存数据、释放资源等操作
                System.out.println("Window is closing...");
                dbUtil.close();
                // 关闭应用程序
                System.exit(0);
            }
        });

    }

    public RTextScrollPane getRTextScrollPane() {
        RSyntaxTextArea rSyntaxTextArea = new RSyntaxTextArea(1, 1);
        rSyntaxTextArea.setAutoIndentEnabled(false);//取消自动缩进
        rSyntaxTextArea.setTabSize(4);
        rSyntaxTextArea.setFont(new Font("宋体", Font.BOLD, 22));
        rSyntaxTextArea.setSyntaxEditingStyle(SyntaxConstants.SYNTAX_STYLE_NONE);
        rSyntaxTextArea.setCodeFoldingEnabled(true);
        RTextScrollPane sp = new RTextScrollPane(rSyntaxTextArea);
        return sp;
    }

}
